using System.Text.RegularExpressions;

namespace UniversalAdminSystem.Domian.PermissionManagement.ValueObjects;

public partial class PermissionResource
{
    public string Value { get; private set; } = null!;

    private PermissionResource(string value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            throw new ArgumentException("资源名称不能为空", nameof(value));
        }

        if (!ENRegex().IsMatch(value))
        {
            throw new ArgumentException("资源名称只能包含英文（小写）、下划线，以 “.” 结构分层，最多支持五层。例如：hantsune.m_i_k_u或初音.未_来", nameof(value));
        }

        Value = value;
    }

    // [GeneratedRegex(@"^[\p{IsCJKUnifiedIdeographs}]+(\.[\p{IsCJKUnifiedIdeographs}]+(_[\p{IsCJKUnifiedIdeographs}]+)*){1,4}$", RegexOptions.Compiled)]
    // private static partial Regex CNRegex();

    [GeneratedRegex(@"^[a-z]+(\.[a-z]+(_[a-z]+)*){0,4}$", RegexOptions.Compiled)]
    private static partial Regex ENRegex();

    /// <summary>
    /// 工厂方法
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static PermissionResource Create(string value) => new(value);

    /// <summary>
    /// 隐式转换string
    /// </summary>
    /// <param name="resource"></param>
    public static implicit operator string(PermissionResource resource) => resource.Value;

    /// <summary>
    /// 显示转换PermissionResource，带验证逻辑
    /// </summary>
    /// <param name="resource"></param>
    public static explicit operator PermissionResource(string resource) => Create(resource);

    /// <summary>
    /// 解析资源层级
    /// </summary>
    /// <returns></returns>
    public IReadOnlyList<string> GetResourceParts()
    {
        return Value.Split('.');
    }

    /// <summary>
    /// 获取顶级模块
    /// </summary>
    /// <returns></returns>
    public string GetModule()
    {
        return Value.Split('.')[0];
    }
}